package my.suveng.alarm;

import cn.hutool.core.util.StrUtil;
import my.suveng.alarm.config.AlarmProperties;
import my.suveng.alarm.dependency.AbstractAlarmEvent;
import my.suveng.alarm.dependency.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;

/**
 * 监听
 * @author suwenguang
 * @date 2020/11/4 9:06 下午
 * @since 1.0
 */
@Component
public class AlarmListener implements ApplicationListener<AbstractAlarmEvent> {
    private static final Logger log = LoggerFactory.getLogger(AlarmListener.class);


    /**
     * 线程池可配置
     */
    private final ExecutorService executor;

    public AlarmListener(ExecutorService executorService, Notify notify, AlarmProperties properties) {
        this.executor = executorService;
        this.notify = notify;
        this.properties = properties;
    }

    /**
     * 通知接口 可配置
     */
    private final Notify notify;

    private final AlarmProperties properties;

    @Override
    public void onApplicationEvent(@NonNull AbstractAlarmEvent event) {
        if (properties.isLogEnable()) {
            log.info(StrUtil.format("接收到告警事件, event:{}", event.toString()));
        }
        executor.submit(() -> notify.send(event.tranfer()));

        if (properties.isLogEnable()) {
            log.info(StrUtil.format("提交告警事件, 完成, event:{}", event.toString()));
        }
    }


}
